const winston = require('winston')
const DailyRotateFile = require('winston-daily-rotate-file')
// 配置日志轮换
const common = {
  datePattern: 'YYYY-MM-DD',
  frequency: '24h',
  maxFiles: '1d', // 保留最近 1 天的日志
  maxSize: '20m', // 单个日志文件最大 20MB
  zippedArchive: true, // 启用压缩
}
const defaultPath = process.env.NODE_ENV === 'development'

const infoTransport = new DailyRotateFile({
  level: 'info',
  filename: defaultPath ? 'logs/%DATE%-info.log' : '/var/logs/%DATE%-info.log',
  ...common,
})

const errorTransport = new DailyRotateFile({
  level: 'error',
  filename: defaultPath
    ? 'logs/%DATE%-error.log'
    : '/var/logs/%DATE%-error.log',
  ...common,
})
const logger = winston.createLogger({
  level: 'info', // 默认日志级别
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    winston.format.printf(({ timestamp, level, message }) => {
      return `${timestamp} [${level}]: ${message}`
    })
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      ),
    }),
    // new winston.transports.File({
    //   filename: './logs/error.log',
    //   level: 'error',
    // }),
    // new winston.transports.File({ filename: './logs/combined.log' }),
    infoTransport,
    errorTransport,
  ],
})

module.exports = logger
